import mongoose, { Document, Schema } from 'mongoose';
import { IChargingRecord } from '@/types';

export interface IChargingRecordDocument
  extends Omit<IChargingRecord, '_id'>,
    Document {}

const chargingRecordSchema = new Schema<IChargingRecordDocument>(
  {
    userId: {
      type: String,
      required: [true, '用户ID是必需的'],
    },
    vehicleId: {
      type: String,
      required: [true, '车辆ID是必需的'],
    },
    date: {
      type: Date,
      required: [true, '充电日期是必需的'],
      default: Date.now,
    },
    odometer: {
      type: Number,
      required: [true, '里程表是必需的'],
      min: [0, '里程表不能为负数'],
    },
    unitPrice: {
      type: Number,
      required: [true, '单价是必需的'],
      min: [0, '单价不能为负数'],
    },
    quantity: {
      type: Number,
      required: [true, '充电量是必需的'],
      min: [0, '充电量不能为负数'],
    },
    totalAmount: {
      type: Number,
      required: [true, '总金额是必需的'],
      min: [0, '总金额不能为负数'],
    },
    actualUnitPrice: {
      type: Number,
      min: [0, '实付单价不能为负数'],
    },
    discountAmount: {
      type: Number,
      min: [0, '优惠金额不能为负数'],
    },
    actualAmount: {
      type: Number,
      min: [0, '实付金额不能为负数'],
    },
    isFullCharge: {
      type: Boolean,
      default: false,
    },
    isLowBatteryWarning: {
      type: Boolean,
      default: false,
    },
    isLastRecordMissed: {
      type: Boolean,
      default: false,
    },
    notes: {
      type: String,
      trim: true,
      maxlength: [500, '备注不能超过500个字符'],
    },
    imageUrl: {
      type: String,
      trim: true,
    },
  },
  {
    timestamps: true,
  }
);

// 索引
chargingRecordSchema.index({ userId: 1 });
chargingRecordSchema.index({ vehicleId: 1 });
chargingRecordSchema.index({ date: 1 });
chargingRecordSchema.index({ userId: 1, vehicleId: 1 });
chargingRecordSchema.index({ userId: 1, date: 1 });
chargingRecordSchema.index({ vehicleId: 1, date: 1 });

export const ChargingRecord = mongoose.model<IChargingRecordDocument>(
  'ChargingRecord',
  chargingRecordSchema
);
